/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* PmProjectServiceAuto
* 项目基本信息
*
* 修改纪录
* 2020-05-18 版本：1.0 liwanpeng 创建。
* @version 版本：1.0
* @author 作者：liwanpeng
* 创建日期：2020-05-18
*/

package com.topscomm.pm.service.impl.auto;

import com.topscomm.basic.IBasicDao;
import com.topscomm.cbo.pojo.CboItemDetailsEntity;
import com.topscomm.cbo.service.impl.CboItemDetailsService;
import com.topscomm.pm.PmService;
import com.topscomm.pm.dao.IPmProjectDao;
import com.topscomm.pm.pojo.PmBudgetLineEntity;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.service.IPmBudgetLineService;
import com.topscomm.pm.service.impl.PmProjectService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.common.DatacodeCache;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;


public class PmProjectServiceAuto extends PmService<PmProjectEntity,IPmProjectDao> {
	@Autowired
	private CboItemDetailsService cboItemDetailsService;

	@Autowired
	private PmProjectService pmProjectService;

	/**
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @param mapRow
	 * @description:设置字段显示值
	 * @modify:
	 */
	@SneakyThrows
	@Override
	public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache){
		String temp;
		StringBufferProxy sql = new StringBufferProxy();

		String ownerdeptcode = ConvertUtil.convertToString(mapRow.get("ownerdeptcode"));
		if(ownerdeptcode.startsWith("26")){
			//科远的赋空值
			mapRow.put("saleprovince","");
		}
		else if("D1F01_0102".equals(ownerdeptcode)){
			//陕西国电
			mapRow.put("saleprovince","51");
		}else if(ownerdeptcode.startsWith("D22F01")){
			//四川分公司
			mapRow.put("saleprovince","34");
		}else if(ownerdeptcode.startsWith("D22F02")){
			//重庆分公司
			mapRow.put("saleprovince","21");
		}else if(ownerdeptcode.startsWith("D22F03")){
			//河北分公司
			mapRow.put("saleprovince","44");
		}else if(ownerdeptcode.startsWith("D22F04")){
			//湖南分公司
			mapRow.put("saleprovince","25");
		}else{
			if(ownerdeptcode.length()>3){
				String deptcode4 = ownerdeptcode.substring(0, 4);
				CboItemDetailsEntity entdept = cboItemDetailsService.queryObjectByWhere("itemid in (select id from CboItems where code='PmPorvinceDept') and code='" + deptcode4 + "'");
				if(entdept!=null){
					mapRow.put("saleprovince",entdept.getExtendfield1()); //省份
				}
			}
		}

		// 项目报表的列表展示"所属区域"字段
		// 逻辑：1>先根据部门编码判断是否为一级部门，如果是一级部门的，直接展示“省区公共”
		//      2>不是一级部门的话，从CRM系统获取对应的区域信息。如果返回来有值，则对部门名称做处理，截取最后一段的字符串再展示，如果返回来的没有值，直接展示“省区公共“
		if (mapRow.get("ownerdeptname") != null && mapRow.get("ownerdeptcode")!=null) {
			String deptnametemp = mapRow.get("ownerdeptname").toString();
			String deptcodetemp= mapRow.get("ownerdeptcode").toString();
			// 判断是否为一级部门
			if((deptcodetemp.contains("_") && deptcodetemp.substring(deptcodetemp.indexOf('_')+1).length()==4)||deptcodetemp.length()==4){
				mapRow.put("dispownerarea","省区公共");
			}else{
				String querycode="";
				if(deptcodetemp.contains("_")){
					querycode=deptcodetemp.substring(0,deptcodetemp.indexOf('_')+7);
				}else{
					querycode=deptcodetemp.length()>=6?deptcodetemp.substring(0,6):deptcodetemp;
				}
				try {
					String areaInfoFromCrmForquery = pmProjectService
						.getAreaInfoFromCrmForquery(querycode);
					if(!Strings.isEmpty(areaInfoFromCrmForquery)){
						// 1>因为CRM中也配置了一级部门的区域编码(CRM系统的需要)，所以需要判断是否包含"区域"二字
						// 2>有的区域部门没有"区域"二字，比如新疆的一些区域部门,所以还需要根据部门code做判断
						if(deptcodetemp.contains("区域")||(deptcodetemp.contains("_") && deptcodetemp.substring(deptcodetemp.indexOf('_')+1).length()==6)||deptcodetemp.length()==6){
							String[] split = deptnametemp.split("\\\\");
							mapRow.put("dispownerarea",split[split.length-1]);
						} else{
							mapRow.put("dispownerarea","省区公共");
						}
					}else{
						mapRow.put("dispownerarea","省区公共");
					}
				} catch (Exception e) {
					throw new Exception("外部系统配置区域编码有误，请联系本系统管理员！");
				}
			}
		}
		if (mapRow.get("projectlevel") != null) {
			temp = mapRow.get("projectlevel").toString();
			mapRow.put("dispprojectlevel", datacodeCache.getValueDynamic("PmProjectLevel", temp, "code", "name"));
		}
		if (mapRow.get("overduestatus") != null) {
			temp = mapRow.get("overduestatus").toString();
			mapRow.put("dispoverduestatus", datacodeCache.getValueDynamic("PmProjectOverdueState", temp, "code", "name"));
		}
		if (mapRow.get("projectstate") != null) {
			temp = mapRow.get("projectstate").toString();
			mapRow.put("dispprojectstate", datacodeCache.getValueDynamic("PmProjectState", temp, "code", "name"));
		}
		if (mapRow.get("category") != null) {
			temp = mapRow.get("category").toString();
			mapRow.put("dispcategory", datacodeCache.getValueDynamic("PmProjectCategory", temp, "code", "name"));
		}
		if (mapRow.get("isincludeproducts") != null) {
			temp = mapRow.get("isincludeproducts").toString();
			mapRow.put("dispisincludeproducts", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("ispurchase") != null) {
			temp = mapRow.get("ispurchase").toString();
			mapRow.put("dispispurchase", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("flowid") != null) {
			temp = mapRow.get("flowid").toString();
			mapRow.put("dispflowid", datacodeCache.getValueDynamic("ApprovalFlow_PmProject", temp, "id", "name"));
		}
		if (mapRow.get("state") != null) {
			temp = mapRow.get("state").toString();
			mapRow.put("dispstate", datacodeCache.getValueDynamic("TapApprovalBillState", temp, "code", "name"));
		}
		if (mapRow.get("enabled") != null) {
			temp = mapRow.get("enabled").toString();
			mapRow.put("dispenabled", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
		}
		if (mapRow.get("province") != null) {
			temp = mapRow.get("province").toString();
			mapRow.put("dispprovince", datacodeCache.getValueDynamic("province", temp, "code", "name"));
		}
		if(mapRow.get("saleprovince")!=null){
			temp = mapRow.get("saleprovince").toString();
			sql.clear();
			sql.appendSingle("EXTENDFIELD1='{0}'", temp);
			List<CboItemDetailsEntity> cboItemDetailsEntities = cboItemDetailsService
				.queryByWhere(sql.toString());
			if(cboItemDetailsEntities.size()!=0){
				mapRow.put("dispsaleprovince",cboItemDetailsEntities.get(0).getName());
			}
		}
		// 客户名称转换==============================开始====================

//		if (mapRow.get("customercode") != null) {
//			temp = mapRow.get("customercode").toString();
//			IPmCustomerService pmCustomerService= (IPmCustomerService)SpringUtil.getBean("pmCustomerService");
//			PmCustomerEntity queryById = pmCustomerService.queryById(temp);
//			mapRow.put("customername", queryById.getName());
//		}
		if (mapRow.get("customercode") != null) {
			temp = mapRow.get("customercode").toString();
			mapRow.put("dispcustomercode", datacodeCache.getValueDynamic("PmCustomer", temp, "id", "name"));
		}


		// 客户名称转换==============================结束====================

		// 预计毛利率
		// 获取当前项目下所有的预算（包括审核未通过的）总金额==============================开始====================
		IPmBudgetLineService pmBudgetLineService= (IPmBudgetLineService)SpringUtil.getBean("pmBudgetLineService");
		StringBufferProxy bugetLineListAllSql = new StringBufferProxy();
		bugetLineListAllSql.appendSingle("projectid = '{0}'",ConvertUtil.convertToString(mapRow.get("id")));
		List<PmBudgetLineEntity> bugetLineListAll = pmBudgetLineService.queryByWhere(bugetLineListAllSql.toString());
		BigDecimal totalBudget = new BigDecimal("0.0000");
		for(PmBudgetLineEntity item:bugetLineListAll) {
			BigDecimal tempBugdgetMoney = new BigDecimal(item.getBudgetmoney());
			totalBudget=totalBudget.add(tempBugdgetMoney);
		}
		DecimalFormat decimalFormat = new DecimalFormat("##.00%");
		// 获取当前项目下所有的预算（包括审核未通过的）总金额==============================结束====================
		// 当前毛利率，获取当前项目下已通过审核的预算总金额==============================开始====================
		StringBufferProxy bugetLineListCureentSql = new StringBufferProxy();

		bugetLineListCureentSql.appendSingle("projectid = '{0}'  and state=9",ConvertUtil.convertToString(mapRow.get("id")));

		List<PmBudgetLineEntity> bugetLineListCureent = pmBudgetLineService.queryByWhere(bugetLineListCureentSql.toString());
		BigDecimal totalBudgetCurrent = new BigDecimal("0.0000");
		for(PmBudgetLineEntity item:bugetLineListCureent) {
			BigDecimal tempBugdgetMoney = new BigDecimal(item.getBudgetmoney());
			totalBudgetCurrent=totalBudgetCurrent.add(tempBugdgetMoney);
		}
		// 当前毛利率，获取当前项目下已通过审核的预算总金额==============================结束====================
		BigDecimal projectMoney = ConvertUtil.convertToBigDecimal(mapRow.get("projectmoney"));// 项目金额
		mapRow.put("estimateProfitRate", projectMoney.compareTo(BigDecimal.ZERO) != 0 ? (projectMoney.subtract(totalBudget)).divide(projectMoney,4).setScale(4) : BigDecimal.ZERO);// 预计毛利率
		mapRow.put("estimateProfitRateForMobile", projectMoney.compareTo(BigDecimal.ZERO) != 0 ? decimalFormat.format((projectMoney.subtract(totalBudget)).divide(projectMoney,4).setScale(4)) : BigDecimal.ZERO);// 预计毛利率
		mapRow.put("currentProfitRate", projectMoney.compareTo(BigDecimal.ZERO) != 0 ? projectMoney.subtract(totalBudgetCurrent).divide(projectMoney,4).setScale(4) : BigDecimal.ZERO);// 预计毛利率
		mapRow.put("currentProfitRateForMobile", projectMoney.compareTo(BigDecimal.ZERO) != 0 ? decimalFormat.format(projectMoney.subtract(totalBudgetCurrent).divide(projectMoney,4).setScale(4)) : BigDecimal.ZERO);// 预计毛利率
	}

	@Override
	@Resource(name = "pmProjectDao")
	public void setDao(IBasicDao<PmProjectEntity> dao) {
		super.setDao(dao);
	}
}
